﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
using SysSU.Net;
using PdfSharp.Pdf.Printing;

namespace PrintService
{
    public class Program
    {
        private static IDictionary<string, string> printers;

        static void Main(string[] args)
        {
            printers = new Dictionary<string, string>();
            printers["Laboratório de P&D em Design"] = @"hp LaserJet 1320 PCL6";
            printers["Sala de Prototipagem 01"] = @"hp LaserJet 1320 PCL6";
            printers["Sala de Prototipagem 02"] = @"hp LaserJet 1320 PCL6";

            while (true)
            {
                try
                {
                    var result = getFile("readsync");

                    if(result.Files.Length > 0)
                    {
                        var user = result.Files[0].User;
                        var file = result.Files[0].Name;
                        var location = getLocation(user);

                        if (location.Users.Length > 0 && printers.ContainsKey(printers[location.Users[0].Location]))
                        {
                            Console.WriteLine(
                                String.Format("Printing file '{0}' from user '{1}' on printer '{2}'.", file, user, printers[location.Users[0].Location]));
                            PdfFilePrinter.AdobeReaderPath = Settings.Default.Acrobat;
                            var printer = new PdfFilePrinter(@"files\" + file, printers[location.Users[0].Location]);
                            printer.Print();
                            getFile("take");
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error: " + ex.Message);
                }
            }
        }

        private static ResponseFileQuery getFile(string operation)
        {
            var jsonRequest = JsonConvert.SerializeObject(new RequestFileQuery("print.great", operation));
            var client = new TCPNetworkClient(Settings.Default.Address, Settings.Default.Port);
            var jsonResult = client.SendMessage(jsonRequest);
            var result = JsonConvert.DeserializeObject(jsonResult, typeof(ResponseFileQuery)) as ResponseFileQuery;
            return result;
        }

        private static ResponseUserQuery getLocation(string user)
        {
            var jsonRequest = JsonConvert.SerializeObject(new RequestUserQuery("print.great", user));
            var client = new TCPNetworkClient(Settings.Default.Address, Settings.Default.Port);
            var jsonResult = client.SendMessage(jsonRequest);
            var result = JsonConvert.DeserializeObject(jsonResult, typeof(ResponseUserQuery)) as ResponseUserQuery;
            return result;
        }
    }
}
